<?php

namespace App\Http\Controllers;

use App\Models\User;
use GuzzleHttp\Client;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $client = new Client();
        $code = $request->code;
        $mptype = $request->mptype;
        $name = $request->name;
        $avatar = $request->avatar;

        switch ($mptype){
            case 'toutiao':
                $request = $client->post('https://developer.toutiao.com/api/apps/v2/jscode2session',[
                    'headers' => ['content-type' => 'application/json'],
                    'json'=>[
                        'appid'  => env('MP_TOUTIAO_APP_ID'),
                        'secret' => env('MP_TOUTIAO_APP_SECRET'),
                        'code'   => $code,
                    ]
                ]);
                break;
        }

        $response = json_decode($request->getBody()->getContents(),true);

        if ($response['err_no'] != 0){
            return $response['err_tips'];
        }

        $open_id = $response['data']['openid'];
        $union_id = $response['data']['openid'];

        $user = User::query()->where('provider',$mptype)->where('openid',$open_id)->where('unionid',$union_id)->first();
        if (!$user){
            // 注册用户
            $user = User::query()->create([
                'nickname' => $name,
                'avatar'   => $avatar,
                'provider' => $mptype,
                'openid'   => $open_id,
                'unionid'   => $union_id,
            ]);
        }

        // 手动登录用户
        $token = $user->createToken($user->id)->plainTextToken;

        return $this->response(['token' => $token]);
    }
}
